﻿using System;
using SharpGL;

namespace MutsiEngine
{
    class Camera
    {
        public float AspectRatio { get { return aspectRatio; } set { aspectRatio = value; projectionMatrix.Matrix = Matrix4x4.CreatePerspectiveFieldOfView(FOV, value, 0.1f, 10000.0f); updateProjectionMat = true; updateModelViewMat = true; } }

        public Vector3 Position;
        public Vector3 Target;
        public Vector3 Up = Vector3.Up;

        public float FOV = 50;
        public float NearClipPlane = 0.1f;
        public float FarClipPlane = 20.0f;

        public Matrix4x4 projectionMatrix;
        public Matrix4x4 modelViewMatrix;

        private float aspectRatio = 4f / 3f;

        private bool updateProjectionMat = true;
        private bool updateModelViewMat = true;

        public Camera()
        {
            Position = new Vector3(0, 0, 0);
            Target = new Vector3(0,0,1f);
            projectionMatrix.Matrix = Matrix4x4.CreatePerspectiveFieldOfView(FOV, aspectRatio, 0.1f, 10000.0f);
            modelViewMatrix.Matrix = Matrix4x4.CreateLookDirection(Position, Target, Up);
        }

        public void SetGLPerspective(OpenGL gl)
        {
            if (updateProjectionMat)
            {
                gl.MatrixMode(MatrixMode.Projection);
                gl.LoadMatrix(projectionMatrix.Matrix);
                updateProjectionMat = false;
            }
        }

        public void SetGLLookAt(OpenGL gl)
        {
            if (updateModelViewMat)
            {
                gl.MatrixMode(MatrixMode.Modelview);
                gl.LoadMatrix(modelViewMatrix.Matrix);
                gl.Translate(-Position.X, -Position.Y, -Position.Z);
                updateModelViewMat = false;
            }
        }

        public void Move(Vector3 offset){
            Position += offset;
            updateModelViewMat = true;
        }

    }
}
